<template>
	<view class="container">
		<!-- 固定在底部的蓝色按钮 -->
		<view class="fixed-button" @click="handleButtonClick">
			<image src="/static/Frame(3).png" class="images" />
			开播
		</view>

		<!-- 顶部背景图容器 -->
		<view class="header-container">
			<!-- 背景图 -->
			<image class="header-bg" src="/static/Mask group.png" mode="widthFix" />
			<!-- 搜索栏 -->
			<view class="search-bar" @click="navigateToSearch">
				<uni-search-bar placeholder="搜索相关直播名称" radius="100" @confirm="handleSearch" bgColor="#ffffff"
					cancelButton="none" />
			</view>
		</view>

		<!-- 分类标签 -->
		<view class="tabs-container">
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
					:class="{ active: activeTab === index }" @click="switchTab(index)">
					{{ tab }}
				</view>
			</view>
		</view>

		<!-- 关注的人展示区域 -->
		<view class="followed-users-container">
			<view class="followed-users-grid">
				<!-- 显示最多4条数据，超过时第4条显示为··· -->
				<view v-for="(user, index) in displayedFollowedUsers" :key="user.id" class="user-item"
					@click="index === 3 && followedUsers.length > 4 ? showAllFollowedUsers() : navigateToUser(user)">
					<view class="user-avatar-container">
						<view class="avatar-border">
							<!-- 第4条且数据超过4条时显示省略号 -->
							<view v-if="index === 3 && followedUsers.length > 4" class="more-avatar">···</view>
							<image v-else class="user-avatar" :src="user.avatar" mode="aspectFill" />
						</view>
						<!-- 直播标识（省略号不显示） -->
						<view v-if="user.isLive && !(index === 3 && followedUsers.length > 4)" class="live-badge">
							<image src="/static/Frame 3.png" mode="" style="width: 3vw;height: 3vw;"></image>
						</view>
					</view>
					<text class="user-name">
						{{ (index === 3 && followedUsers.length > 4) ? '更多' : user.name }}
					</text>
				</view>
			</view>
		</view>

		<!-- 直播列表 - 添加下拉刷新功能 -->
		<scroll-view class="live-list" scroll-y @scrolltolower="loadMore" refresher-enabled
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh">
			<!-- 两列网格布局 -->
			<view class="grid-container">
				<view v-for="(item, index) in liveList" :key="index" class="live-item" @click="navigateToLive(item)">
					<!-- 封面图容器 -->
					<view class="cover-container">
						<!-- 状态标签 - 现在位于封面图左上角 -->
						<view class="status-tag" :class="getStatusClass(item.status)">
							<image v-if="getStatusIcon(item.status)" :src="getStatusIcon(item.status)"
								class="status-icon" mode="aspectFit" />
							{{ getStatusText(item.status) }}
						</view>

						<image class="cover" :src="item.cover" mode="aspectFill" />
						<!-- 覆盖在图片上的文字信息 -->
						<view class="cover-overlay">
							<!-- 标题 -->
							<text class="cover-title">{{ item.title || '未命名直播' }}</text>

							<!-- 底部信息栏 -->
							<view class="cover-bottom">
								<!-- 直播中显示观看人数 -->
								<view class="cover-info" v-if="item.status === STATUS.LIVE">
									<uni-icons type="eye" size="12" color="rgba(255,255,255,0.8)"></uni-icons>
									<text>{{ formatNumber(item.viewers) }}人在看</text>
								</view>

								<!-- 预告显示时间 -->
								<view class="cover-info" v-if="item.status === STATUS.UPCOMING">
									<uni-icons type="calendar" size="12" color="rgba(255,255,255,0.8)"></uni-icons>
									<text>{{ formatTime(item.time) }}开播</text>
								</view>

								<!-- 回放显示时长 -->
								<view class="cover-info" v-if="item.status === STATUS.REPLAY">
									<uni-icons type="videocam" size="12" color="rgba(255,255,255,0.8)"></uni-icons>
									<text>{{ formatDuration(item.duration) }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more">
				<text v-if="loading">加载中...</text>
				<text v-else-if="noMore">没有更多了</text>
			</view>

			<!-- 底部安全区域 -->
			<view class="safe-area"></view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'

	// 状态常量
	const STATUS = {
		LIVE: 1, // 直播中
		UPCOMING: 2, // 预告
		REPLAY: 3 // 回放
	}

	// 数据
	const tabs = ref(['全部', '直播中', '预告', '回放'])
	const activeTab = ref(0)
	const liveList = ref([])
	const loading = ref(false)
	const noMore = ref(false)
	const page = ref(1)
	const pageSize = 10
	const refreshing = ref(false) // 下拉刷新状态
	const maxPage = 50 // 最大页数

	// 封面图片数组
	const coverImages = [
		'/static/image-my/Group 11095.png',
		'/static/logo.png',
		'/static/login/Frame 5.png'
	]

	// 模拟关注用户数据
	const followedUsers = ref([{
			id: 1,
			name: '张三',
			avatar: '/static/logo.png',
			isLive: true
		},
		{
			id: 2,
			name: '李四',
			avatar: '/static/logo.png',
			isLive: true
		},
		{
			id: 3,
			name: '王五',
			avatar: '/static/logo.png',
			isLive: true
		},
		{
			id: 4,
			name: '赵六',
			avatar: '/static/logo.png',
			isLive: true
		},
		{
			id: 5,
			name: '钱七',
			avatar: '/static/logo.png',
			isLive: true
		}
	])

	// 计算属性：最多显示4条数据
	const displayedFollowedUsers = computed(() => {
		return followedUsers.value.slice(0, 4)
	})

	// 添加到观看记录
	const addToWatchHistory = (item) => {
		uni.getStorage({
			key: 'watchHistory',
			success: (res) => {
				let history = res.data || []
				// 检查是否已存在
				const exists = history.some(historyItem => historyItem.id === item.id)
				if (!exists) {
					// 添加观看时间
					const record = {
						...item,
						watchTime: new Date().getTime()
					}
					// 添加到数组开头
					history.unshift(record)
					// 限制最多保存50条记录
					if (history.length > 50) {
						history.pop()
					}
					// 保存到本地存储
					uni.setStorage({
						key: 'watchHistory',
						data: history
					})
				}
			},
			fail: () => {
				// 如果没有存储过，创建新记录
				const record = {
					...item,
					watchTime: new Date().getTime()
				}
				uni.setStorage({
					key: 'watchHistory',
					data: [record]
				})
			}
		})
	}

	// 生成模拟数据函数
	const generateMockData = (count, status) => {
		const types = status === 0 ? [STATUS.LIVE, STATUS.UPCOMING, STATUS.REPLAY] : [status]
		const result = []
		const anchors = ['张三', '李四', '王五', '赵六', '钱七']

		for (let i = 0; i < count; i++) {
			const type = types[Math.floor(Math.random() * types.length)]
			const baseId = Math.floor(Math.random() * 10000)
			const anchorIndex = Math.floor(Math.random() * anchors.length)
			const coverIndex = Math.floor(Math.random() * coverImages.length)

			const item = {
				id: baseId + i,
				title: getRandomTitle(type),
				time: getRandomTime(type),
				cover: coverImages[coverIndex], // 使用预设的封面图片
				status: type,
				viewers: type === STATUS.LIVE ? Math.floor(Math.random() * 10000) : 0,
				duration: type === STATUS.REPLAY ? Math.floor(Math.random() * 7200) : 0,
				anchor: anchors[anchorIndex] // 添加主播名称
			}
			result.push(item)
		}
		return result
	}

	const getRandomTitle = (type) => {
		const prefixes = {
			[STATUS.LIVE]: ['正在直播', '精彩直播', '热门直播'],
			[STATUS.UPCOMING]: ['即将开始', '精彩预告', '不容错过'],
			[STATUS.REPLAY]: ['精彩回放', '往期回顾', '经典重现']
		}
		const suffixes = ['产品发布会', '技术分享会', '年度盛典', '新品预售', '专家讲座']
		const prefix = prefixes[type][Math.floor(Math.random() * prefixes[type].length)]
		const suffix = suffixes[Math.floor(Math.random() * suffixes.length)]
		return `${prefix}: ${suffix}`
	}

	const getRandomTime = (type) => {
		const now = new Date()
		if (type === STATUS.LIVE) {
			return now.toISOString()
		} else if (type === STATUS.UPCOMING) {
			const future = new Date(now.getTime() + Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000))
			return future.toISOString()
		} else {
			const past = new Date(now.getTime() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000))
			return past.toISOString()
		}
	}

	// 生命周期
	onLoad(() => {
		fetchLiveList()
	})

	// 方法
	const fetchLiveList = () => {
		if (page.value > maxPage) {
			noMore.value = true
			loading.value = false
			return
		}

		loading.value = true
		setTimeout(() => {
			// 生成模拟数据
			const newData = generateMockData(pageSize, activeTab.value === 0 ? 0 : activeTab.value)

			if (refreshing.value) {
				// 下拉刷新时替换全部数据
				liveList.value = newData
				page.value = 1
				refreshing.value = false
				uni.stopPullDownRefresh()
			} else {
				// 上拉加载时追加数据
				liveList.value = [...liveList.value, ...newData]
			}

			loading.value = false
			noMore.value = newData.length < pageSize || page.value >= maxPage
		}, 1000)
	}

	// 下拉刷新
	const onRefresh = () => {
		if (loading.value) return
		refreshing.value = true
		noMore.value = false
		fetchLiveList()
	}

	// 上拉加载更多
	const loadMore = () => {
		if (loading.value || noMore.value || refreshing.value) return
		page.value++
		fetchLiveList()
	}

	const switchTab = (index) => {
		if (activeTab.value === index) return
		activeTab.value = index
		liveList.value = []
		page.value = 1
		noMore.value = false
		fetchLiveList()
	}

	// 开播
	const handleButtonClick = () => {
		uni.navigateTo({
			url: '/pages/start/start' // 跳转到start页面
		})
	}

	const handleSearch = (e) => {
		console.log('搜索:', e.value)
		uni.showToast({
			title: `搜索: ${e.value}`,
			icon: 'none'
		})
	}

	const navigateToLive = (item) => {
		// 如果是直播状态，添加到观看记录
		if (item.status === STATUS.LIVE) {
			addToWatchHistory(item)
		}

		let url = ''
		switch (item.status) {
			// 预告
			case STATUS.UPCOMING:
				url = `/pages/preview/preview?id=${item.id}`
				break
				// 直播
			case STATUS.LIVE:
				url = `/pages/broadcast/broadcast?id=${item.id}`
				break
				// 回放 
			case STATUS.REPLAY:
				url =
					`/pages/playback/playback?id=${item.id}&anchorName=${encodeURIComponent(item.anchor || '主播')}&videoTitle=${encodeURIComponent(item.title || '未命名直播')}`
				break
			default:
				url = `/pages/preview/detail?id=${item.id}`
		}

		uni.navigateTo({
			url
		})
	}

	// 搜索
	const navigateToSearch = () => {
		uni.navigateTo({
			url: '/pages/search/search'
		})
	}

	const navigateToUser = (user) => {
		uni.navigateTo({
			url: `/pages/user/profile?id=${user.id}`
		})
	}

	const showAllFollowedUsers = () => {
		uni.navigateTo({
			url: '/pages/user/followed-list'
		})
	}

	const getStatusText = (status) => {
		switch (status) {
			case STATUS.LIVE:
				return '直播中'
			case STATUS.UPCOMING:
				return '预告'
			case STATUS.REPLAY:
				return '回放'
			default:
				return ''
		}
	}

	const getStatusClass = (status) => {
		switch (status) {
			case STATUS.LIVE:
				return 'live'
			case STATUS.UPCOMING:
				return 'upcoming'
			case STATUS.REPLAY:
				return 'replay'
			default:
				return ''
		}
	}

	const getStatusIcon = (status) => {
		switch (status) {
			case STATUS.LIVE:
				return '/static/Frame 3.png'
			case STATUS.UPCOMING:
				return '/static/Frame(2).png'
			case STATUS.REPLAY:
				return '/static/Frame(1).png'
			default:
				return ''
		}
	}

	const formatDuration = (seconds) => {
		if (!seconds) return '00:00'
		const mins = Math.floor(seconds / 60)
		const secs = seconds % 60
		return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
	}

	const formatTime = (timeStr) => {
		if (!timeStr) return '时间待定'
		try {
			const date = new Date(timeStr)
			if (isNaN(date.getTime())) return '时间待定'
			const hours = date.getHours().toString().padStart(2, '0')
			const minutes = date.getMinutes().toString().padStart(2, '0')
			return `${hours}:${minutes}`
		} catch (e) {
			return '时间待定'
		}
	}

	const formatNumber = (num) => {
		if (typeof num !== 'number' || isNaN(num)) return '0'
		if (num >= 10000) return (num / 10000).toFixed(1) + 'w'
		return num.toString()
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: rgb(247, 247, 247);
		position: relative;
	}

	.images {
		height: 4vh;
		width: 4vh;
		margin-right: 3vw;
	}

	/* 固定在底部的按钮 */
	.fixed-button {
		position: fixed;
		bottom: 10vh;
		left: 50%;
		transform: translateX(-50%);
		width: 35vw;
		height: 7vh;
		background-color: rgba(44, 122, 246);
		color: white;
		border-radius: 25px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 16px;
		font-weight: bold;
		box-shadow: 0 4px 12px rgba(0, 191, 255, 0.3);
		z-index: 100;

		&:active {
			background-color: #0095D9;
			transform: translateX(-50%) scale(0.98);
		}
	}

	/* 顶部背景图容器 */
	.header-container {
		position: relative;
		width: 100%;
		z-index: 1;
	}

	.header-bg {
		width: 100%;
		display: block;
	}

	/* 搜索栏 */
	.search-bar {
		position: absolute;
		width: 90%;
		top: 20px;
		left: 0;
		right: 0;
		padding: 0 16px;
		z-index: 10;
	}

	/* 分类标签容器 */
	.tabs-container {
		padding: 0 16px;
		position: relative;
		z-index: 5;
		margin-top: -120px;
	}

	.tabs {
		display: flex;
		padding-top: 12px;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 12px 0;
		font-size: 14px;
		color: #666;
		position: relative;

		&.active {
			color: #00BFFF;
			font-weight: 500;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 20px;
				height: 3px;
				background-color: #00BFFF;
				border-radius: 3px;
			}
		}
	}

	/* 修改后的关注的人区域 */
	.followed-users-container {
		padding: 12px 16px;
		margin-top: 8px;
		border-radius: 8px;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
	}

	.followed-users-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 10px;
	}

	.user-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.user-avatar-container {
		position: relative;
		width: 60px;
		height: 60px;
		margin-bottom: 6px;
	}

	.avatar-border {
		width: 100%;
		height: 100%;
		border-radius: 55%;
		padding: 3px;
		background: linear-gradient(45deg, #FF9500, #FF5E3A);
		box-shadow: 0 4px 8px rgba(255, 149, 0, 0.3);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.user-avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: #eee;
		border: 2px solid white;
	}

	.more-avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24px;
		font-weight: bold;
	}

	.live-badge {
		position: absolute;
		bottom: 0;
		right: 0;
		width: 18px;
		height: 18px;
		border-radius: 50%;
		background-color: #ff4d4f;
		display: flex;
		justify-content: center;
		align-items: center;
		border: 2px solid white;
		z-index: 2;
	}

	.user-name {
		font-size: 12px;
		color: #666;
		text-align: center;
		width: 100%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/* 直播列表 */
	.live-list {
		flex: 1;
		padding: 8px 0;
		background-color: #f5f5f5;
	}

	.grid-container {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 12px;
		padding: 0 12px;
	}

	.live-item {
		height: 20vh;
		border-radius: 8px;
		overflow: hidden;
		background-color: #fff;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		transition: transform 0.2s;

		&:active {
			transform: scale(0.98);
		}
	}

	.cover-container {
		height: 100%;
		position: relative;
		width: 100%;
		aspect-ratio: 16/9;
		border-radius: 8px;
		overflow: hidden;
	}

	.cover {
		width: 100%;
		height: 100%;
		display: block;
		background-color: #eee;
	}

	/* 修改状态标签定位 */
	.status-tag {
		position: absolute;
		display: flex;
		align-items: center;
		padding: 4px 8px;
		border-radius: 0 0 20rpx 0;
		font-size: 10px;
		font-weight: 500;
		z-index: 2;
		line-height: 1.2;
		color: #fff;
		border: 1px solid rgba(0, 0, 0, 0.1);

		&.live {
			background-color: rgb(255, 90, 67);
		}

		&.upcoming {
			background-color: #00BFFF;
		}

		&.replay {
			background-color: rgb(24, 27, 50);
		}
	}

	.cover-overlay {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 12px;
		background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
		color: #fff;
	}

	.cover-title {
		display: block;
		font-size: 14px;
		font-weight: 500;
		line-height: 1.4;
		margin-bottom: 8px;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
	}

	.cover-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 11px;
		color: rgba(255, 255, 255, 0.8);
	}

	.cover-info {
		display: flex;
		align-items: center;
		gap: 4px;
	}

	.status-icon {
		width: 12px;
		height: 12px;
		margin-right: 2px;
		display: block;
	}

	/* 加载更多 */
	.load-more {
		text-align: center;
		padding: 16px 0;
		font-size: 14px;
		color: #999;
	}

	/* 安全区域 */
	.safe-area {
		height: env(safe-area-inset-bottom);
		height: constant(safe-area-inset-bottom);
	}

	/* 响应式调整 */
	@media (max-width: 320px) {
		.grid-container {
			gap: 8px;
			padding: 0 8px;
		}

		.cover-title {
			font-size: 12px;
		}

		.search-bar {
			padding: 0 10px;
		}

		.tabs-container {
			padding: 0 10px;
		}

		.user-avatar-container {
			width: 50px;
			height: 50px;
		}

		.more-avatar {
			font-size: 20px;
		}

		.followed-users-grid {
			gap: 5px;
		}
	}
</style>